package com.ys.everydaynews.base

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import com.ys.everydaynews.mvp.presenter.BasePresenter
import com.ys.everydaynews.mvp.view.BaseView
import com.ys.everydaynews.ui.main.model.EventModel
import com.ys.everydaynews.utils.SharedPreferencesUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseFragment<V, P : BasePresenter<V>, DB : ViewDataBinding> : Fragment(), BaseView {
    lateinit var binding: DB
    private var mPersenter: P? = null
    private var rootView: View? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    protected abstract fun initView()

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initData()
    }

    protected abstract fun initData()
    protected abstract fun isRegister(): Boolean

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (rootView == null) {
            binding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
            rootView=binding.root
            if (mPersenter == null) {
                mPersenter = createPersenter()
            }
            if (mPersenter != null) {
                mPersenter!!.bindView(this as V)
            }

            if (isRegister()) {
                EventBus.getDefault().register(this)
            }
        }


        return rootView
    }

    protected abstract fun getLayoutId(): Int
    protected abstract fun createPersenter(): P

    fun getPersenter() = mPersenter
    override fun onDestroy() {
        super.onDestroy()
        mPersenter!!.unBindView()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    fun starActivity(clz: Class<*>) {
        startActivity(Intent(activity, clz))
    }

    fun getToken(): String? = SharedPreferencesUtils.getSaveToken(requireActivity(), Constants.TOKEN)
    fun isTokenNotNull(): Boolean = !TextUtils.isEmpty(getToken())

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun getMessage(message: EventModel<*>) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    open fun getMessageSticky(message: EventModel<*>) {

    }

    open fun postMsg(message: EventModel<*>) {
        EventBus.getDefault().post(message)
    }
}